package com.world.rickcloudendpoint.service.runner;

import com.world.rickcloudendpoint.common.constant.GlobalConstants;
import com.world.rickcloudendpoint.demo.redis.RedisQueueSender;
import com.world.rickcloudendpoint.basic.ServerServiceManager;
import com.world.rickcloudendpoint.net.server.ReceptionChannelInitializer;
import com.world.rickcloudendpoint.net.server.ReceptionNetTcpServerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @description: 接收信号 服务启动器
 * @author: jlsong
 * @date: 2021/12/12 11:29:52
 * @version: 1.0
 */
@Component
@Order(1)
public class ReceptionServerRunner implements CommandLineRunner {
    @Value("${netty.tcp.reception.port}")
    private Integer port;

    RedisQueueSender queueSender;

    @Autowired
    public void setQueueSender(RedisQueueSender queueSender) {
        this.queueSender = queueSender;
    }

    /**
     * 接收信号服务
     */
    ReceptionNetTcpServerService server;

    public ReceptionNetTcpServerService getServer(int port, ReceptionChannelInitializer nettyTcpChannelInitializer) {
        return new ReceptionNetTcpServerService(ServerServiceManager.SERVICE_ID_ROOT, port, GlobalConstants.Thread.NET_TCP_BOSS, GlobalConstants.Thread.NET_TCP_WORKER, nettyTcpChannelInitializer);
    }

    ExecutorService pool = new ThreadPoolExecutor(1, 1, 1000, TimeUnit.MILLISECONDS, new LinkedBlockingQueue());


    @Override
    public void run(String... args) throws Exception {
        if (server == null) {
            this.server = getServer(port, new ReceptionChannelInitializer(queueSender));
        }
        pool.execute(() -> {
            try {
                server.startup();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }
}
